<template>
  <div class="illumination" style="position: relative">
    <div class="table-box">
      <div class="select-box">
        <Button v-if="!saved" @click="addButtonClick" type="primary"
        >新增
        </Button
        >
        <Button v-if="!saved" @click="saveClick">保存</Button>
        <Button
                v-else
                type="primary"
                @click="actionButtonClick"
                :disabled="executeDisabled"
        >执行
        </Button
        >
      </div>
      <Table border :columns="columns" :data="tableData"></Table>
    </div>
    <div class="pagination">
      <span
      >共{{ page.totalNum }}条记录 第{{ page.currentPage }}/{{
          Math.ceil(page.totalNum / page.pageSize) || 1
        }}页
      </span>
      <Page
              show-sizer
              @on-change="goPage"
              @on-page-size-change="goPageSize"
              :total="page.totalNum"
              :page-size="page.pageSize"
              :page-size-opts="page.pageSizeOpts"
              show-elevator
      />
    </div>
    <!--新增 -->
    <Modal
            v-model="addFormShow"
            @on-ok="addButtonSubmit"
            class-name="vertical-center-modal"
            :mask-closable="false"
            width="40"
            :loading="modelLoading"
            scrollable
            center
            title="安全校验"
    >
      <div>
        <Form
                ref="addModel"
                :model="addForm"
                :rules="addValidate"
                label-position="right"
                :label-width="110"
        >
          <Row :gutter="20">
            <Col span="24">
              <div class="form-type">
                <img
                        src="../../../../assets/img/userControl/9.png"
                        height="14"
                        width="12"
                />设备选择
              </div>
            </Col>
          </Row>
          <Row>
            <Col span="12">
              <FormItem label="选择用户" prop="custId">
                <Select
                        @on-change="custChange"
                        v-model="addForm.custId"
                        size="small"
                        class=""
                        placeholder="请选择"
                >
                  <Option
                          v-for="(item, index) in userList"
                          :value="item.custId"
                          :key="item.custId + index"
                  >{{ item.custName }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
              <FormItem label="选择设备" prop="equipId">
                <Select
                        @on-change="deviceChange"
                        v-model="addForm.equipId"
                        size="small"
                        class=""
                        placeholder="请先选择用户"
                >
                  <Option
                          v-for="(item, index) in deviceList"
                          :value="item.equipId"
                          :key="item.equipId"
                  >{{ item.equipName }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="设备类型">
                <Input size="small" placeholder="请先选择设备" :disabled="true" v-model="addForm.equipType"></Input>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="24">
              <div class="form-type">
                <img
                        src="../../../../assets/img/userControl/9.png"
                        height="14"
                        width="12"
                />控制设置
              </div>
            </Col>
          </Row>
          <Row>
            <Col span="12" v-if="addForm.isControl == 1 || addForm.isControl == 0">
              <FormItem label="状态设置" prop="action">
                <Select
                        :disabled="addForm.isControl != 1"
                        v-model="addForm.action"
                        size="small"
                        class=""
                        placeholder="请选择"
                >
                  <Option value="0">关</Option>
                  <Option value="1">开</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="addForm.isControl == 2 || addForm.isControl == 0">
              <FormItem label="数值设置" prop="number">
                <Input
                        :disabled="addForm.isControl != 2"
                        type="number"
                        size="small"
                        v-model="addForm.number"
                ></Input>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
    selectDeviceBatchControl,
    selectBaseInfosByCustId,
    batchControlBatchInsert,
    batchControlExecute
} from "@/api/scada";

import moment from "moment";

export default {
    name: "multipleControl",
    isFailed: false,
    failedIndex: 0,
    props: {},
    data() {
        return {
            tabDisabled: false,
            saved: false,
            addFormShow: false,
            modelLoading: true,
            editStatus: false,
            executeDisabled: false,
            editIndex: 0,
            userList: [],
            deviceList: [],
            addForm: {
                custId: "",
                equipId: "",
                equipType: "",
                action: "",
                number: 0,
                isControl: 0
            },
            addValidate: {
                custId: [{required: true, message: "请选择用户", trigger: "blur"}],
                equipId: [{required: true, message: "请选择设备", trigger: "blur"}],
                action: [{required: true, message: "请设置状态", trigger: "blur"}],
                number: [
                    {required: true, message: "请设置数值", trigger: "blur"},
                    {
                        type: "string",
                        message: "请设置一个整数",
                        pattern: /^[1-9]+[0-9]*$/,
                        trigger: "blur"
                    }
                ]
            },
            page: {
                currentPage: 1,
                pageSize: 5,
                totalNum: 0,
                pageSizeOpts: [5, 10, 15, 20]
            },
            columns: [
                {
                    type: "index",
                    width: 100,
                    title: "顺序号",
                    align: "center"
                },
                {title: "区域", key: "areaName"},
                {title: "厂站", key: "siteName"},
                {title: "用户名称", key: "custName"},
                {title: "设备ID", key: "equipId"},
                {title: "设备名称", key: "equipName"},
                {title: "操作项", key: "actionType"},
                {title: "操作值", key: "opValueLabel"},
                {
                    title: "操作",
                    render: (h, params) => {
                        return h("span", [
                            h(
                                "Button",
                                {
                                    props: {
                                        type: "info",
                                        size: "small",
                                        ghost: true,
                                        disabled: this.saved
                                    },
                                    style: {
                                        "margin-right": "8px"
                                    },
                                    nativeOn: {
                                        click: () => {
                                            this.edit(params);
                                        }
                                    }
                                },
                                "修改"
                            ),
                            h(
                                "Button",
                                {
                                    props: {
                                        type: "info",
                                        size: "small",
                                        ghost: true,
                                        disabled: this.saved
                                    },
                                    nativeOn: {
                                        click: () => {
                                            this.delete(params);
                                        }
                                    }
                                },
                                "删除"
                            )
                        ]);
                    }
                }
            ],
            tableData: [],
            dataOriginal: []
        };
    },
    computed: {},
    created() {
    },
    mounted() {
        this.tabDisabled = true;
        selectBaseInfosByCustId().then((res) => {
            if (res.code === 200) {
                this.userList = res.result || [];
            }
        });

        this.initLamp();
    },
    watch: {},
    methods: {
        deviceChange(equipId) {
            this.deviceList.forEach((item) => {
                if (item.equipId === equipId) {
                    this.addForm.equipType = item.equipType;
                    this.addForm.isControl = item.isControl;
                }
            });
        },
        custChange(value) {
            this.getDeviceList(value);
        },
        getDeviceList(value) {
            let data = {
                custId: value
            };
            selectDeviceBatchControl(data).then((res) => {
                const {code, result} = res;
                if (code === 200) {
                    this.deviceList = result;
                }
            });
        },
        saveClick() {
            this.saved = true;
            this.tabDisabled = false;
            let data = this.dataOriginal.map((item, index) => {
                return {
                    ctrNo: index,
                    devId: item.equipId,
                    devType: item.equipType,
                    opValue: item.opValue,
                    custId: item.custId,
                    stId: item.siteId
                };
            });

            batchControlBatchInsert({list: data})
                .then((res) => {
                    const {code, result} = res;
                    if (code === 200) {
                        this.dataOriginal = result;
                        this.columns.pop();
                        this.dataOriginal.forEach((item) => {
                            item.opValueLabel = item.opValue;
                            item.actionType = item.isControl == 1 ? "开关" : "置数";
                        });
                        this.columns.pop();
                        this.initLamp();
                    }
                })
                .finally(() => {
                });
        },
        addTableData() {
            let formInfo = this.addForm;
            let obj = {};
            this.deviceList.forEach((item) => {
                if (item.equipId === formInfo.equipId) {
                    obj = item;
                }
            });

            obj.actionType = formInfo.isControl == 1 ? "开关" : "置数";
            obj.opValue = formInfo.isControl == 2 ? formInfo.number : formInfo.action;
            obj.opValueLabel =
                formInfo.isControl == 2
                    ? formInfo.number
                    : formInfo.action == 1
                    ? "开"
                    : "关";
            if (this.editStatus) {
                this.dataOriginal[this.editIndex] = obj;
                this.editStatus = false;
            } else {
                this.dataOriginal.push(obj);
            }
            this.initLamp();
            this.addForm = {
                custId: "",
                epuipId: "",
                equipType: "",
                action: "",
                number: 0
            };
            this.deviceList = [];
        },
        addButtonSubmit() {
            this.$refs["addModel"].validate((valid) => {
                if (valid) {
                    this.addFormShow = false;
                    this.addTableData();
                } else {
                    this.modelLoading = false;
                    setTimeout(() => {
                        this.modelLoading = true;
                    });
                }
            });
        },
        edit({row}) {
            let index = this.page.pageSize * (this.page.currentPage - 1) + row._index;
            let obj = this.dataOriginal[index];

            this.addForm.custId = obj.custName;
            this.addForm.equipId = obj.equipId;
            this.addForm.equipType = obj.equipType;
            this.addForm.number = obj.opValue;
            this.addForm.action = obj.opValue;
            this.addForm.isControl = obj.isControl;
            this.addFormShow = true;
            this.editStatus = true;
            this.editIndex = index;
        },
        delete({row}) {
            let index = this.page.pageSize * (this.page.currentPage - 1) + row._index;
            this.dataOriginal.splice(index, 1);
            this.initLamp();
        },
        actionButtonClick() {
            let me = this;
            this.$Modal.confirm({
                title: "确认提示",
                content: `是否执行批量指令`,
                onOk: () => {
                    let arr = [
                        {title: "执行状态", key: "executeStatus"},
                        {title: "执行时间", key: "executeTime"},
                        {title: "告警信息", key: "warningMessage"}
                    ];
                    me.columns.push(...arr);
                    this.dataOriginal.forEach((item) => {
                        item.executeStatus = "等待执行";
                    });
                    this.initLamp();
                    me.execute();
                },
                onCancle: () => {
                }
            });
        },
        async execute(i = 0) {
            let me = this;
            this.executeDisabled = true;
            if (this.isFailed) {
                i = this.failedIndex + 1;
                this.isFailed = false;
            }
            let data = this.dataOriginal[i];
            let res;
            try {
                data.executeTime = moment(new Date()).format("yyyy-MM-DD hh:mm:ss");
                data.executeStatus = "正在执行";
                this.initLamp();
                res = await batchControlExecute(data);
            } catch (e) {
                console.log(e);
            }
            setTimeout(() => {
                this.executeDisabled = false;
            }, 100);
            if (res.code === 200) {
                data.executeStatus = "成功";
                if (this.dataOriginal.length > i + 1) {
                    this.execute(i + 1);
                }
            } else {
                data.executeStatus = "失败";
                data.warningMessage = res.result;
                this.$Modal.confirm({
                    title: "提示",
                    content: `第${i}条指令失败，请问是否继续后续指令`,
                    onOk: () => {
                        me.execute(i + 1);
                    },
                    onCancle: () => {
                        me.isFailed = true;
                        me.failedIndex = i;
                    }
                });
            }
            this.initLamp();
        },
        addButtonClick() {
            this.addFormShow = true;
        },
        goPageSize(page) {
            this.page.pageSize = page;
            this.initLamp();
        },
        goPage(page) {
            this.page.currentPage = page;
            this.initLamp();
        },
        initLamp() {
            this.page.totalNum = this.dataOriginal.length;
            let start = this.page.pageSize * (this.page.currentPage - 1);
            let end = this.page.pageSize;
            this.tableData = this.dataOriginal.slice(start, start + end);
        }
    },
    components: {}
};
</script>

<style scoped lang="scss">
  .form-type {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    color: #008df0;
    font-size: 14px;
    > img {
      margin-right: 2px;
    }
  }

  ::v-deep .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal {
      top: 0;
    }
  }

  .illumination {
    display: flex;
    flex-direction: column;
    background: white;
    border-radius: 5px;
    .title {
      font-size: 16px;
      height: 40px;
      line-height: 40px;
      padding-left: 15px;
      color: #333;
      font-weight: 500;
      border-bottom: 1px solid #c7c7c7;
      position: relative;
      width: 100%;
    }
    .table-box {
      margin: 0 15px;
      /*box-shadow: 2px 2px 4px 0px rgba(0, 0, 0, 0.13);*/
      .select-box {
        padding-bottom: 15px;
        .select-item {
          width: 120px;
          margin-right: 10px;
        }
      }
    }
  }

  .illumination .pagination {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
  }

  .illumination .pagination span {
    font-size: 14px;
    font-family: SimSun;
    font-weight: 400;
    color: #666666;
  }
</style>
<style lang="scss" scoped>
  /deep/ .ivu-table-tip table tr td {
    text-align: center;
    background-image: url("~@/assets/img/zwsj.png");
    background-position: center 60px;
    background-repeat: no-repeat;
    color: #999;
    height: 369px;
    background-size: 190px;
    span {
      display: none;
    }
  }
</style>
